package com.erp.app.admin.systemMenu.web;

//JRE Classes
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.erp.app.admin.systemMenu.beans.SystemMenuGroupVO;
import com.erp.app.admin.systemMenu.ejb.SystemMenuGroupPK;
import com.erp.app.common.ProjectConstants;
import com.erp.app.util.web.WebUtil;
import com.erp.framework.controller.action.SimpleMaintStyleAction;
import com.erp.framework.controller.form.SimpleMaintStyleForm;
import com.erp.framework.model.pk.SimpleBasePk;
import com.erp.framework.model.vo.SimpleBaseVo;
import com.erp.framework.util.CommonUtil;
import com.erp.framework.util.logger.Logger;
import com.erp.framework.util.user.User;

public class SystemMenuMaintenanceAction extends SimpleMaintStyleAction {

    final private String actionAddMenuObject = "addMenuObject";
    final private String actionDelMenuObject = "delMenuObject";

    public final String actionAddMenuGroupIcon = "addMenuGroupIcon";
    public final String actionViewMenuGroupIcon = "viewMenuGroupIcon";
    public final String actionDelMenuGroupIcon = "delMenuGroupIcon";

    public final String statusAddMenuGroupIcon = "addMenuGroupIcon";

    public final String actionAddMenuGroupImage = "addMenuGroupImage";
    public final String actionViewMenuGroupImage = "viewMenuGroupImage";
    public final String actionDelMenuGroupImage = "delMenuGroupImage";

    public final String statusAddMenuGroupImage = "addMenuGroupImage";

    protected ActionForward handlePageEvent(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        
        
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        String action = form.getPageEvent();
        action = CommonUtil.isEmpty(action) ? "" : action.trim();
        ActionForward actionForward = new ActionForward(mapping.getInput());

        String rb_status = CommonUtil.nullToString((String) session.getAttribute(getSessionSimpleMaintStatus()));
        // System.out.println("handlePageEvent() action=" + action);
        // System.out.println("handlePageEvent() isHandled=" +
        // isHandled(request));
        System.out.println("SystemMenuAction, updateDate=" + form.getUpdateDate());

        if (!isHandled(request) && action.equalsIgnoreCase(actionAddMenuObject)) {
            setHandled(request);
            actionForward = processActionAddMenuObject(mapping, formIn, request, response, errors);
            saveToken(request);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionDelMenuObject)) {
            setHandled(request);
            actionForward = processActionDelMenuObject(mapping, formIn, request, response, errors);
            saveToken(request);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionAddMenuGroupIcon)) {
            setHandled(request);
            actionForward = processActionAddMenuGroupIcon(mapping, formIn, request, response, errors);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionViewMenuGroupIcon)) {
            setHandled(request);
            actionForward = processActionViewMenuGroupIcon(mapping, formIn, request, response, errors);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionDelMenuGroupIcon)) {
            setHandled(request);
            actionForward = processActionDelMenuGroupIcon(mapping, formIn, request, response, errors);
            saveToken(request);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionAddMenuGroupImage)) {
            setHandled(request);
            actionForward = processActionAddMenuGroupImage(mapping, formIn, request, response, errors);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionViewMenuGroupImage)) {
            setHandled(request);
            actionForward = processActionViewMenuGroupImage(mapping, formIn, request, response, errors);
        } else if (!isHandled(request) && action.equalsIgnoreCase(actionDelMenuGroupImage)) {
            setHandled(request);
            actionForward = processActionDelMenuGroupImage(mapping, formIn, request, response, errors);
            saveToken(request);
        }

        return actionForward;
    }

    protected ActionForward processOtherStatus(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {

        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        HttpSession session = request.getSession(false);

        ActionForward actionForward = new ActionForward(mapping.getInput());

        if (rb_status.equals(statusAddMenuGroupIcon)) {
            return processStatusAddMenuGroupIcon(mapping, formIn, request, response, errors, rb_status);
        } else if (rb_status.equals(statusAddMenuGroupImage)) {
            return processStatusAddMenuGroupImage(mapping, formIn, request, response, errors, rb_status);
        }

        return actionForward;
    }

    protected ActionForward processActionAddMenuObject(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        String action = CommonUtil.nullToString(form.getAction());
        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        try {
            SystemMenuObjectRow rowToAdd = new SystemMenuObjectRow();
            form.setCurrIdx(0);

            rowToAdd.setCompanyCode(form.getCompanyCode());
            rowToAdd.setGroupId(form.getGroupId());
            rowToAdd.setMenuId(form.getMenuId());
            rowToAdd.setIsDelete("");

            form.addRow(rowToAdd);
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        }

        return actionForward;
    }

    protected ActionForward processActionDelMenuObject(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        String action = CommonUtil.nullToString(form.getAction());
        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        // ArrayList rows = form.getMultiRows(0);
        ArrayList rows = form.getFinalRows();

        int idx = Integer.parseInt(form.getPageEventSrc());
        SystemMenuObjectRow rowToEdit = (SystemMenuObjectRow) rows.get(idx);
        rowToEdit.setIsDelete("checked");

        // form.setCurrIdx(0);
        form.setRow(idx, rowToEdit);

        return actionForward;
    }

    protected ActionForward processStatusAddMenuGroupIcon(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        try {
            HashMap params = (HashMap) session.getAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);
            session.removeAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);

            if (params == null)
                return actionForward;

            FormFile file = (FormFile) params.get(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_FORM_FILE);

            if (file == null)
                return actionForward;

            // retrieve the file name
            String fileName = file.getFileName();

            // retrieve the content type
            String contentType = file.getContentType();

            // retrieve the file data
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream stream = file.getInputStream();

            if (!CommonUtil.isEmpty(fileName)) {

                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }

                form.setIconContentType(contentType);
                form.setMenuIcon(baos.toByteArray());
            }
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.toString()));
        }

        return actionForward;
    }

    // for menu group logo
    protected ActionForward processActionAddMenuGroupIcon(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        HashMap params = new HashMap();
        LinkedList keyList = new LinkedList();

        keyList.add("Company Code");
        keyList.add(form.getCompanyCode());
        keyList.add("Group Id");
        keyList.add(form.getGroupId());
        keyList.add("Menu Id");
        keyList.add(form.getMenuId());

        params.put(ProjectConstants.SESSION_KEY_LIST, keyList);
        params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_NAME, getSessionSimpleMaintStatus());
        params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_VALUE, statusAddMenuGroupIcon);
        params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
        session.setAttribute(ProjectConstants.SESSION_UPLOAD_FILE_PARAM, params);

        return actionForward;
    }

    protected ActionForward processActionViewMenuGroupIcon(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        actionForward = null;

        try {
            OutputStream out = response.getOutputStream();
            response.setContentType(form.getIconContentType());
            response.setStatus(response.SC_OK);
            byte[] content = form.getMenuIcon();
            out.write(content);
            out.close();
            return null;
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        }

        return actionForward;
    }

    protected ActionForward processActionDelMenuGroupIcon(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        try {
            // a little bit different
            // only set byte array null
            form.setMenuIcon(null);
            form.setIconContentType(null);
        } catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.toString()));
            Logger.logExceptions(this, e);
        }

        return actionForward;
    }

    // end of menu group logo part

    protected ActionForward processStatusAddMenuGroupImage(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors, String rb_status) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        User editingUser = (User) session.getAttribute(ProjectConstants.SESSION_USER);

        try {
            HashMap params = (HashMap) session.getAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);
            session.removeAttribute(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_PARAM);

            if (params == null)
                return actionForward;

            FormFile file = (FormFile) params.get(ProjectConstants.SESSION_UPLOAD_FILE_RETURN_FORM_FILE);

            if (file == null)
                return actionForward;

            // retrieve the file name
            String fileName = file.getFileName();

            // retrieve the content type
            String contentType = file.getContentType();

            // retrieve the file data
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InputStream stream = file.getInputStream();

            if (!CommonUtil.isEmpty(fileName)) {

                byte[] buffer = new byte[8192];
                int bytesRead = 0;
                while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                    baos.write(buffer, 0, bytesRead);
                }

                form.setImageContentType(contentType);
                form.setMenuImage(baos.toByteArray());
            }
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.toString()));
        }

        return actionForward;
    }

    // for menu group logo
    protected ActionForward processActionAddMenuGroupImage(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        HashMap params = new HashMap();
        LinkedList keyList = new LinkedList();

        keyList.add("Company Code");
        keyList.add(form.getCompanyCode());
        keyList.add("Group Id");
        keyList.add(form.getGroupId());
        keyList.add("Menu Id");
        keyList.add(form.getMenuId());

        params.put(ProjectConstants.SESSION_KEY_LIST, keyList);
        params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_NAME, getSessionSimpleMaintStatus());
        params.put(ProjectConstants.SESSION_UPLOAD_FILE_SESSION_VALUE, statusAddMenuGroupImage);
        params.put(ProjectConstants.SESSION_OPENER_PATH, getFunctionId());
        session.setAttribute(ProjectConstants.SESSION_UPLOAD_FILE_PARAM, params);

        return actionForward;
    }

    protected ActionForward processActionViewMenuGroupImage(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        actionForward = null;

        try {
            OutputStream out = response.getOutputStream();
            response.setContentType(form.getImageContentType());
            response.setStatus(response.SC_OK);
            byte[] content = form.getMenuImage();
            out.write(content);
            out.close();
            return null;
        } catch (Exception e) {
        	Logger.logExceptions(this, e);
        }

        return actionForward;
    }

    protected ActionForward processActionDelMenuGroupImage(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());

        try {
            // a little bit different
            // only set byte array null
            form.setMenuImage(null);
            form.setImageContentType(null);
        } catch (Exception e) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("exception.general", e.toString()));
            Logger.logExceptions(this, e);
        }

        return actionForward;
    }

    // end of menu group logo part

    protected String getFunctionId() {
        return "systemMenuMaintenance.do";
    }

    protected Class getMasterFormClass() {
        return SystemMenuMaintenanceForm.class;
    }

    protected Class getMasterVOClass() {
        return SystemMenuGroupVO.class;
    }

    protected Class[] getChildRowClass() {
        // Class[] childRowClass = new Class[2];
        Class[] childRowClass = new Class[1];

        childRowClass[0] = com.erp.app.admin.systemMenu.web.SystemMenuObjectRow.class;

        return childRowClass;
    }

    protected String[] getFolderChildIdxMapping() {
        // String[] folderChildIdx = new String[2];
        String[] folderChildIdx = new String[1];

        folderChildIdx[0] = "0";
        // folderChildIdx[1] = "1";

        return folderChildIdx;
        // return null;
    }

    protected String getSessionSimpleSearchStatus() {
        return ProjectConstants.SESSION_SIMPLE_SEARCH_STATUS;
    }

    protected String getSessionSimpleMaintStatus() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_STATUS;
    }

    protected String getSessionSimpleMaintPk() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_PK;
    }

    protected String getSessionSimpleMaintInitModel() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_INIT_MODEL;
    }

    protected String getSessionSimpleMaintEditType() {
        return ProjectConstants.SESSION_SIMPLE_MAINT_EDIT_TYPE;
    }

    protected String getSessionMasterMaintDelegate() {
        return "SESSION_SM_DELEGATE";
    }

    protected String getSessionAlertAfterSave() {
        return ProjectConstants.SESSION_ALERT_AFTER_SAVE;
    }

    protected String getSessionAlertAfterDelete() {
        return ProjectConstants.SESSION_ALERT_AFTER_DELETE;
    }

    protected String getModuleName(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response) {
        return ProjectConstants.MOD_SYSTEM_MENU_MAINT;
    }

    protected String getSessionReset() {
        return ProjectConstants.SESSION_SIMPLE_SEARCH_RESET;
    }

    protected SimpleBasePk getPk(ActionForm formIn, HttpServletRequest request) {
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        SystemMenuGroupPK pk = new SystemMenuGroupPK(form.getCompanyCode(), form.getGroupId(), form.getMenuId());
        return pk;
    }

    protected boolean getKeepSearchResult() {
        return true;
    }

    protected String getSessionFolderIdx() {
        // return "cons.menu.maintenance.folderIdx";
        return "cons.remarkMaster.maintenance.folderIdx";

        // return Constants.SESSION_SIMPLE_MAIN_FOLDER_IDX;
    }

    protected void setSessionFolderIdx(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response) {
        HttpSession session = request.getSession(false);
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;

        session.setAttribute(getSessionFolderIdx(), form.getFolderIdx());
    }

    protected SimpleBaseVo getInitialzedModel(ActionForm form, User editingUser) {
        return null;
    }

    protected void beforeValidate(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        
        

        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        ActionForward actionForward = new ActionForward(mapping.getInput());
        // User editingUser = (User)
        // session.getAttribute(Constants.SESSION_USER);

    }

//    protected void otherValidate(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
//            HttpServletResponse response, ActionErrors errors) {
//    }

    private int getNextSequence(Collection c, String seqPropertyName) throws Exception {

        int currentSeqNo, maxSeqNo = 1;
        Iterator iterator = c.iterator();
        while (iterator.hasNext()) {
            Object obj = iterator.next();
            String seqNo = (String) PropertyUtils.getSimpleProperty(obj, seqPropertyName);
            currentSeqNo = Integer.parseInt(seqNo);
            if (currentSeqNo >= maxSeqNo) {
                maxSeqNo = currentSeqNo + 1;
            }
        }
        return maxSeqNo;
    }

    protected void initAction(ActionMapping mapping, ActionForm formIn, HttpServletRequest request, HttpServletResponse response) {
    }

    protected void beforeCreate(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors) {

        HttpSession session = request.getSession(false);
        
        
        SystemMenuMaintenanceForm form = (SystemMenuMaintenanceForm) formIn;
        String companyCode = WebUtil.getAppropriateCompanyCode(session, ProjectConstants.SP_SHARE_SYSTEM_MENU);

        form.setCompanyCode(companyCode);
        // form.setGroupId(((User)session.getAttribute(Constants.SESSION_USER)).getRoleGroupId());

    }

    protected String getMasterFormSessionName() {
        return "systemMenuMaintenanceForm";
    }


    protected void setFormType(ActionMapping mapping, ActionForm formIn, HttpServletRequest request,
            HttpServletResponse response, ActionErrors errors){
        SimpleMaintStyleForm form = (SimpleMaintStyleForm)formIn;
        form.setFormType(ProjectConstants.FORM_TYPE_MAINT);
    }
    
}
